/*
 * Interface.java
 *
 * Created on 28 de Agosto de 2008, 20:59
 */

package chat;

import java.awt.Color;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author  Jeffom
 */
public class Interface extends javax.swing.JFrame {
    boolean camponome = false;
    boolean campoip = false;
    Cliente cliente;
    Servidor server;
    /** Creates new form Interface */
    public Interface() {       
        initComponents();
        NomeField.setVisible(false);
        IpField.setVisible(false);
        ConectButton.setVisible(false);
        ServidorButton.setVisible(false);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        MsgField = new javax.swing.JTextField();
        MsgButton = new javax.swing.JButton();
        ConectButton = new javax.swing.JButton();
        IpField = new javax.swing.JTextField();
        NomeField = new javax.swing.JTextField();
        ServidorButton = new javax.swing.JButton();
        jMenuBar2 = new javax.swing.JMenuBar();
        MenuFile1 = new javax.swing.JMenu();
        ServidorMenu = new javax.swing.JMenuItem();
        ConectarMenu = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        SairMenu1 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        MsgField.setText("jTextField1");

        MsgButton.setText("Mensagem");
        MsgButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MsgButtonActionPerformed(evt);
            }
        });

        ConectButton.setText("Conectar");
        ConectButton.setEnabled(false);
        ConectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConectButtonActionPerformed(evt);
            }
        });

        IpField.setText("Ip");
        IpField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                IpFieldFocusGained(evt);
            }
        });

        NomeField.setText("Nome");
        NomeField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                NomeFieldFocusGained(evt);
            }
        });

        ServidorButton.setText("Criar Servidor");
        ServidorButton.setEnabled(false);
        ServidorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ServidorButtonActionPerformed(evt);
            }
        });

        MenuFile1.setText("File");

        ServidorMenu.setText("Criar Servidor");
        ServidorMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ServidorMenuActionPerformed(evt);
            }
        });
        MenuFile1.add(ServidorMenu);

        ConectarMenu.setText("Conectar...");
        ConectarMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConectarMenuActionPerformed(evt);
            }
        });
        MenuFile1.add(ConectarMenu);
        MenuFile1.add(jSeparator2);

        SairMenu1.setText("Sair");
        SairMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SairMenu1ActionPerformed(evt);
            }
        });
        MenuFile1.add(SairMenu1);

        jMenuBar2.add(MenuFile1);

        jMenu3.setText("Edit");
        jMenuBar2.add(jMenu3);

        setJMenuBar(jMenuBar2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(MsgButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(MsgField, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(IpField)
                            .addComponent(NomeField, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
                            .addComponent(ConectButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(ServidorButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(139, 139, 139)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(NomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(IpField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(ServidorButton)
                .addGap(1, 1, 1)
                .addComponent(ConectButton)
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(MsgField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(MsgButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ConectarMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConectarMenuActionPerformed
        // TODO add your handling code here:
        /* Código para habilitar o botão de conectar apenas quando os dois estivere 
        preenchidos (Não necessariamente corretamente)*/        
        NomeField.setVisible(true);
        IpField.setVisible(true);
        ConectButton.setVisible(true);
        
        if(ServidorButton.isVisible())
            ServidorButton.setVisible(false);
        
        NomeField.getDocument().addDocumentListener(
        new DocumentListener(){

        String str;

                public void insertUpdate(DocumentEvent e) {
                    camponome = true;
                    if(campoip)
                        ConectButton.setEnabled(true);
                }

                public void removeUpdate(DocumentEvent e) {
                    str = NomeField.getText();
                    if (str.length() < 1)
                        ConectButton.setEnabled(false);
                    camponome = false;
                }

                public void changedUpdate(DocumentEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });

            IpField.getDocument().addDocumentListener(
            new DocumentListener(){
              String str;

                public void insertUpdate(DocumentEvent e) {
                    campoip = true;
                    if(camponome)
                        ConectButton.setEnabled(true);
                }

                public void removeUpdate(DocumentEvent e) {
                    str = IpField.getText();
                    if (str.length() < 1)
                        ConectButton.setEnabled(false);
                    campoip = false;
                }

                public void changedUpdate(DocumentEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            }); 
    }//GEN-LAST:event_ConectarMenuActionPerformed

    private void NomeFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_NomeFieldFocusGained
        // TODO add your handling code here:
        NomeField.selectAll();
    }//GEN-LAST:event_NomeFieldFocusGained

    private void IpFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_IpFieldFocusGained
        // TODO add your handling code here:
        IpField.selectAll();
    }//GEN-LAST:event_IpFieldFocusGained

    private void ServidorMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ServidorMenuActionPerformed
        // TODO add your handling code here:        ;    
       ServidorButton.setVisible(true);      
       NomeField.setVisible(true);
       if(ConectButton.isVisible())
       {
           ConectButton.setVisible(false);
           IpField.setVisible(false);
       }
       
       
        NomeField.getDocument().addDocumentListener(
        new DocumentListener(){

        String str;

                public void insertUpdate(DocumentEvent e) {
                    camponome = true;
                    ServidorButton.setEnabled(true);
                }

                public void removeUpdate(DocumentEvent e) {
                    str = NomeField.getText();
                    if (str.length() < 1)
                        ServidorButton.setEnabled(false);
                    camponome = false;
                }

                public void changedUpdate(DocumentEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });

      
    }//GEN-LAST:event_ServidorMenuActionPerformed

    private void ConectButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        try {
            // TODO add your handling code here:
            cliente = new Cliente();
            //cliente.Conectar(IpField.getText(), 1234);
            cliente.Conectar("127.0.0.1", 1234);
            if(cliente.getSocket().isConnected())
            {
                jTextArea1.append("Conexão feita com sucesso" + "\n");
                cliente.setNome(NomeField.getText());
                //cliente.run();                
                new Chat(cliente.getSocket(),this);
            }            
        } catch (UnknownHostException ex) {
            Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                            

    private void ServidorButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
        try {
            // TODO add your handling code here:
            //Inicia a thread do servidor e do chat
            server = new Servidor();
            server.CriarServer();
            
            if(server.getSocket().isConnected()){                
                jTextArea1.append("Cliente conectado");
                server.setNome(NomeField.getText());
                //server.run();
                new Chat(server.getSocket(),this);
            }
            
        } catch (IOException ex) {
            //Erro 
            Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void SairMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SairMenu1ActionPerformed
        // TODO add your handling code here:
        System.exit(1);
    }//GEN-LAST:event_SairMenu1ActionPerformed

    private void MsgButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MsgButtonActionPerformed

            // TODO add your handling code here:
        ObjectOutputStream out;      
        
        if(cliente != null)
        {
            try {
                out = new ObjectOutputStream(cliente.getSocket().getOutputStream());
                Pacote pack = new Pacote("chat", MsgField.getText(), cliente.getNome());
                out.writeObject(pack);
                out.flush();
            } catch (IOException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else if(server != null)
        {
            try {
                out = new ObjectOutputStream(server.getSocket().getOutputStream());
                Pacote pack = new Pacote("chat", MsgField.getText(), server.getNome());
                out.writeObject(pack);
                out.flush();
            } catch (IOException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        
    }//GEN-LAST:event_MsgButtonActionPerformed
    
    public void setTextBox(String args)
    {
        jTextArea1.append(args);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Interface().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ConectButton;
    private javax.swing.JMenuItem ConectarMenu;
    private javax.swing.JTextField IpField;
    private javax.swing.JMenu MenuFile1;
    private javax.swing.JButton MsgButton;
    private javax.swing.JTextField MsgField;
    private javax.swing.JTextField NomeField;
    private javax.swing.JMenuItem SairMenu1;
    private javax.swing.JButton ServidorButton;
    private javax.swing.JMenuItem ServidorMenu;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
      
}
